# -*- coding: utf-8 -*-
"""
HaaS506 RTU 存储模块
简化版本 - 数据存储和KV存储
"""

import ujson as json
import utime
import kv

# 存储配置
_flash_cache = []
_max_cache_size = 100
_kv_initialized = False

def init():
    """初始化存储模块"""
    global _kv_initialized
    
    try:
        # 初始化KV存储
        _kv_initialized = True
        
        # 增加重启次数
        _increment_reboot_count()
        
        print("[STORAGE] Storage module initialized")
        return True
        
    except Exception as e:
        print("[STORAGE] Init error: {}".format(e))
        return False

def _increment_reboot_count():
    """增加重启次数"""
    try:
        # 获取重启次数，kv.get返回字符串
        count_str = kv.get("reboot_count")
        if count_str:
            count = int(count_str)
        else:
            count = 0
        count += 1
        # kv.set需要字符串
        kv.set("reboot_count", str(count))
        print("[STORAGE] Reboot count: {}".format(count))
    except Exception as e:
        print("[STORAGE] Reboot count error: {}".format(e))

def get_reboot_count():
    """获取重启次数"""
    try:
        count_str = kv.get("reboot_count")
        if count_str:
            return int(count_str)
        return 0
    except:
        return 0

def set_kv(key, value):
    """设置KV值"""
    if not _kv_initialized:
        return False
    
    try:
        # kv.set需要字符串类型
        if isinstance(value, (dict, list)):
            kv.set(key, json.dumps(value))
        else:
            kv.set(key, str(value))
        return True
    except Exception as e:
        print("[STORAGE] Set KV error: {}".format(e))
        return False

def get_kv(key, default=None):
    """获取KV值"""
    if not _kv_initialized:
        return default
    
    try:
        value = kv.get(key)
        if value is None:
            return default
        
        # 尝试解析JSON
        try:
            return json.loads(value)
        except:
            # 如果不是JSON，返回字符串
            return value
    except Exception as e:
        print("[STORAGE] Get KV error: {}".format(e))
        return default

def cache_data(data):
    """缓存数据到Flash"""
    global _flash_cache
    
    try:
        # 添加时间戳
        data_with_time = {
            "timestamp": utime.time(),
            "data": data
        }
        
        _flash_cache.append(data_with_time)
        
        # 限制缓存大小
        if len(_flash_cache) > _max_cache_size:
            _flash_cache.pop(0)
        
        # 定期保存到文件
        if len(_flash_cache) % 10 == 0:
            _save_cache_to_file()
        
        return True
        
    except Exception as e:
        print("[STORAGE] Cache data error: {}".format(e))
        return False

def get_cached_data():
    """获取缓存的数据"""
    try:
        # 先尝试从内存获取
        if _flash_cache:
            return _flash_cache.copy()
        
        # 从文件加载
        return _load_cache_from_file()
        
    except Exception as e:
        print("[STORAGE] Get cached data error: {}".format(e))
        return []

def save_cache():
    """立即保存缓存到文件（公共接口）"""
    try:
        if _flash_cache:
            print("[STORAGE] Saving {} cached items to file".format(len(_flash_cache)))
            return _save_cache_to_file()
        else:
            print("[STORAGE] No cached data to save")
            return True
    except Exception as e:
        print("[STORAGE] Save cache error: {}".format(e))
        return False

def clear_cache():
    """清空缓存"""
    global _flash_cache
    
    try:
        _flash_cache.clear()
        _delete_cache_file()
        return True
    except Exception as e:
        print("[STORAGE] Clear cache error: {}".format(e))
        return False

def _save_cache_to_file():
    """保存缓存到文件"""
    try:
        # 使用/flash/目录来持久存储
        with open("/flash/data_cache.txt", "a") as f:
            for item in _flash_cache:
                f.write(json.dumps(item) + "\n")
        # 清空内存缓存
        _flash_cache.clear()
        return True
    except Exception as e:
        print("[STORAGE] Save cache file error: {}".format(e))
        return False

def _load_cache_from_file():
    """从文件加载缓存"""
    try:
        print("[STORAGE-DEBUG] Loading cache file...")
        
        # 检查文件是否存在
        try:
            cache_data = []
            max_items = 100  # 限制最大加载条目数
            line_num = 0
            with open("/flash/data_cache.txt", "r") as f:
                for line in f:
                    if line_num >= max_items:
                        print("[STORAGE-DEBUG] Reached max cache items limit: {}".format(max_items))
                        break
                    
                    line = line.strip()
                    if line:
                        # 检查行大小
                        if len(line) > 2048:  # 单行最大2KB
                            print("[STORAGE-DEBUG] Skip oversized line: {} bytes".format(len(line)))
                            line_num += 1
                            continue
                        
                        try:
                            data = json.loads(line)
                            cache_data.append(data)
                        except ValueError as e:
                            print("[STORAGE-DEBUG] Skip invalid JSON: {}".format(line[:50]))
                            line_num += 1
                            continue
                        except MemoryError:
                            print("[STORAGE-DEBUG] Out of memory loading cache")
                            break
                        except Exception as e:
                            print("[STORAGE-DEBUG] Skip invalid line: {}".format(line[:50]))
                            line_num += 1
                            continue
                    
                    line_num += 1
            
            print("[STORAGE-DEBUG] Loaded {} items from cache".format(len(cache_data)))
            return cache_data
                
        except OSError:
            print("[STORAGE-DEBUG] Cache file does not exist")
            return []
            
    except Exception as e:
        print("[STORAGE] Load cache file error: {}".format(e))
        print("[STORAGE] Error type: {}".format(type(e)))
        return []

def _delete_cache_file():
    """删除缓存文件"""
    try:
        # 清空文件内容而不是删除文件
        with open("/flash/data_cache.txt", "w") as f:
            f.write("")
        return True
    except Exception as e:
        print("[STORAGE] Delete cache file error: {}".format(e))
        return False

def save_system_time():
    """保存系统时间"""
    try:
        current_time = utime.time()
        set_kv("last_time", current_time)
        return True
    except Exception as e:
        print("[STORAGE] Save system time error: {}".format(e))
        return False

def get_last_time():
    """获取上次保存的时间"""
    try:
        return get_kv("last_time", 0)
    except:
        return 0

def get_storage_stats():
    """获取存储统计信息"""
    try:
        cache_count = len(_flash_cache)
        reboot_count = get_reboot_count()
        last_time = get_last_time()
        
        return {
            "cache_count": cache_count,
            "reboot_count": reboot_count,
            "last_time": last_time,
            "kv_initialized": _kv_initialized
        }
    except Exception as e:
        print("[STORAGE] Get storage stats error: {}".format(e))
        return None

def test_storage():
    """测试存储功能"""
    print("[STORAGE] Testing storage...")
    
    # 测试KV存储
    test_key = "test_key"
    test_value = "test_value"
    
    if set_kv(test_key, test_value):
        retrieved_value = get_kv(test_key)
        if retrieved_value == test_value:
            print("[STORAGE] KV storage test passed")
        else:
            print("[STORAGE] KV storage test failed")
    
    # 测试数据缓存
    test_data = {"temperature": 25.5, "humidity": 60.0}
    if cache_data(test_data):
        cached_data = get_cached_data()
        if cached_data:
            print("[STORAGE] Data cache test passed: {} items".format(len(cached_data)))
        else:
            print("[STORAGE] Data cache test failed")
    
    # 显示存储统计
    stats = get_storage_stats()
    print("[STORAGE] Storage stats: {}".format(stats))
    
    print("[STORAGE] Storage test completed")

def save_reboot_reason(reason):
    """保存重启原因"""
    try:
        timestamp = utime.time()
        reboot_info = {
            "reason": reason,
            "timestamp": timestamp,
            "formatted_time": _format_time(timestamp)
        }
        kv.set("last_reboot_reason", json.dumps(reboot_info))
        print("[STORAGE] Reboot reason saved: {}".format(reason))
    except Exception as e:
        print("[STORAGE] Save reboot reason error: {}".format(e))

def get_reboot_reason():
    """获取重启原因"""
    try:
        reason_str = kv.get("last_reboot_reason")
        if reason_str:
            return json.loads(reason_str)
        return None
    except Exception as e:
        print("[STORAGE] Get reboot reason error: {}".format(e))
        return None

def save_system_error(error_msg):
    """保存系统错误信息"""
    try:
        timestamp = utime.time()
        error_info = {
            "error": error_msg,
            "timestamp": timestamp,
            "formatted_time": _format_time(timestamp)
        }
        kv.set("last_system_error", json.dumps(error_info))
        print("[STORAGE] System error saved: {}".format(error_msg))
    except Exception as e:
        print("[STORAGE] Save system error error: {}".format(e))

def get_system_error():
    """获取系统错误信息"""
    try:
        error_str = kv.get("last_system_error")
        if error_str:
            return json.loads(error_str)
        return None
    except Exception as e:
        print("[STORAGE] Get system error error: {}".format(e))
        return None

def increment_reboot_count():
    """增加重启次数（外部调用）"""
    return _increment_reboot_count()

def _format_time(timestamp):
    """格式化时间戳"""
    try:
        import utime
        time_tuple = utime.localtime(timestamp)
        return "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
            time_tuple[0], time_tuple[1], time_tuple[2], 
            time_tuple[3], time_tuple[4], time_tuple[5]
        )
    except:
        return str(timestamp)